import { JSONFilePreset } from 'lowdb/node'
import { v4 as uuidv4 } from 'uuid';
import cache from  'memory-cache'
export  function test(req, res) {
    res.json({t:0,d:'hello'});
}
export  function test2(req, res) {
    res.json({t:0,userid:res.locals.userid });
}
export async function adduser(req, res) {
    const db = await JSONFilePreset('db.json',  { user: [] })
    let users = db.data.user
    const lastId = users.length ? users[users.length - 1].id : 0;
    console.log(req.body)
    let {username,password} = req.body
    password = password ?? '111111'
    const newUser = { id: lastId + 1, username,password};
    users.push(newUser)
    await db.write()
    res.send(newUser.id +"")
}

export async function getToken(req, res) {
    let authorization = req.headers["authorization"].substring(6); // basic xxxxxxx
    const buff = Buffer.from(authorization, 'base64');
    const str = buff.toString('utf-8');
    const [username,password] = str.split(":");
    const db = await JSONFilePreset('db.json',  { user: [] })
    const user = db.data.user.filter(i => username)[0]
    console.log(user)
    const tokenValue =uuidv4();
    const tokenName = 'satoken'
    let tokenTimeout = -1
    if(user && user.password === password){
        cache.put(tokenValue,user,60*60*24*365)
        res.json({tokenValue,tokenName,tokenTimeout}) // 这里返回token 信息
    }else{
        res.status(401).json({code:401,message:'用户名或密码错误'});
    }
}

export function logout(req, res){
    cache.del(res.locals.token)
    res.send('')
}
